package sf01.studentmngmsystem.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import sf01.studentmngmsystem.common.Result;
import sf01.studentmngmsystem.entity.Student;
import sf01.studentmngmsystem.entity.Teacher;
import sf01.studentmngmsystem.service.StudentService;

import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/students")
@Validated
public class StudentController {
    
    @Autowired
    private StudentService studentService;
    
    /**
     * 分页查询学生列表（支持排序）
     */
    @GetMapping
    public Result getStudentsWithPagination(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String major,
            @RequestParam(required = false) String classNumber,
            @RequestParam(required = false) String sortField,
            @RequestParam(required = false) String sortOrder) {
        
        Map<String, Object> result = studentService.getStudentsWithPagination(
            page, size, name, major, classNumber, sortField, sortOrder);
        return Result.success(result);
    }
    
    /**
     * 批量删除学生（优化版）
     */
    @DeleteMapping("/batch")
    public Result batchDeleteStudents(
            @RequestBody @NotEmpty(message = "删除列表不能为空") List<Long> studentIds) {
        try {
            studentService.batchDeleteStudentsOptimized(studentIds);
            return Result.success("批量删除成功，共删除 " + studentIds.size() + " 条记录");
        } catch (Exception e) {
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }
    
    @GetMapping("/{id}")
    public Result getStudentById(@PathVariable Long id) {
        try {
            Student student = studentService.getStudentById(id);
            if (student != null) {
                return Result.success(student);
            } else {
                return Result.error("学生不存在");
            }
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    @PostMapping
    public Result addStudent(@Valid @RequestBody Student student) {
        try {
            studentService.addStudent(student);
            return Result.success("添加成功");
        } catch (Exception e) {
            return Result.error("添加失败：" + e.getMessage());
        }
    }
    
    @PutMapping("/{id}")
    public Result updateStudent(@PathVariable Long id, @Valid @RequestBody Student student) {
        try {
            student.setId(id);
            studentService.updateStudent(student);
            return Result.success("更新成功");
        } catch (Exception e) {
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result deleteStudent(@PathVariable Long id) {
        try {
            studentService.deleteStudent(id);
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 数据导出功能
     */
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportStudents(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String major,
            @RequestParam(required = false) String classNumber) {
        try {
            byte[] excelData = studentService.exportStudents(name, major, classNumber);
            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=students.xlsx")
                    .header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                    .body(excelData);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 全局异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationExceptions(MethodArgumentNotValidException ex) {
        String errorMessage = ex.getBindingResult().getFieldErrors().stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining("; "));
        return Result.error("数据验证失败: " + errorMessage);
    }
    
    // 在现有的StudentController类中添加以下方法
    
    /**
     * 检查教师登录状态
     */
    private boolean isTeacherLoggedIn(HttpSession session) {
        return session.getAttribute("teacher") != null;
    }
    
    /**
     * 显示学生管理页面（需要教师权限）
     */
    @GetMapping("/students")
    public String showStudentsPage(HttpSession session, Model model) {
        // 检查教师是否已登录
        if (!isTeacherLoggedIn(session)) {
            return "redirect:/teacher/login";
        }
        
        // 获取教师信息并传递给页面
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        model.addAttribute("teacherName", teacher.getName());
        
        return "students";
    }
}